package model.autoupgrade.download;

import java.io.File;
import java.io.IOException;
import java.util.Properties;

import aimee.common.FTPConnection;
import aimee.common.Logger;
import aimee.common.RegexUtils;
import model.autoupgrade.version.SqlQuery;

public class PackageDownloadFromFtp implements PackageDownload
{
	private static Properties properties;
	private static String ftpHost;
	private static String ftpUsername;
	private static String ftpPassword;
	static
	{
		try
		{
			properties = new Properties();
			properties.load(SqlQuery.class.getResourceAsStream("/autoupdate.properties"));
			ftpHost = properties.getProperty("ftp.host");
			ftpUsername = properties.getProperty("ftp.username");
			ftpPassword = properties.getProperty("ftp.password");
		}
		catch (IOException e)
		{
			Logger.error(e.getMessage(), e);
		}
	}
	
	@Override
	public File download(String address, String localPath)
	{
		try(FTPConnection connection = new FTPConnection(ftpHost, 21, ftpUsername, ftpPassword))
		{
			new File(localPath).mkdirs();
			String fileName = RegexUtils.find(address, ".*/(.*)$");
			String ftpPath = RegexUtils.find(address, "(.*/).*$");
			File file = connection.download(fileName, ftpPath, localPath);
			return file;
		}
		catch (Exception e)
		{
			Logger.error(e.getMessage(), e);
		}
		return null;
	}
	
	public static void main(String[] args)
	{
		String s1 = "/tag/planee/4.5.0/win32/plan_4.5.0_win32_release_patch[entire]_2018-07-17_17-17.zip";
		PackageDownload packageDownload = new PackageDownloadFromFtp();
		packageDownload.download(s1, "D:/11");
	}

}
